package com.bank.task;

import com.bank.constant.AccountStatus;
import com.bank.constant.MessageConstant;
import com.bank.entity.Account;
import com.bank.entity.AccountStatusLog;
import com.bank.entity.LoanTransaction;
import com.bank.mapper.AccountMapper;
import com.bank.mapper.AccountStatusMapper;
import com.bank.mapper.LoanTransactionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;

@Configuration
@Slf4j
public class AccountStatusTask {
    @Autowired
    private AccountStatusMapper accountStatusMapper;
    @Autowired
    private LoanTransactionMapper loanTransactionMapper;
    @Autowired
    private AccountMapper accountMapper;

    @Scheduled(cron = "0/1 * * * * ?")
    public void frozenAccountStatusTask() {
        // 扫描loan_transaction表，找到逾期未付款的账户
        loanTransactionMapper.getExpiredNotPaidLoanAccounts().forEach(accountId -> {
            // 对于逾期未付款的账户，将其状态设置为冻结
            accountMapper.setAccountStatus(accountId, AccountStatus.FROZEN);

            // 插入冻结记录到account_status表中
            Account account = accountMapper.getAccountById(accountId);
            AccountStatusLog accountStatusLog = AccountStatusLog.builder()
                    .accountId(account.getAccountId())
                    .oldStatus(account.getStatus())
                    .newStatus(AccountStatus.FROZEN)
                    .changeTime(LocalDateTime.now())
                    .reason(MessageConstant.EXPIRED_NOT_PAID)
                    .build();
            accountStatusMapper.insert(accountStatusLog);
        });
    }
}
